//
//  ItemAddController.swift
//  Fancyswap
//
//  Created by Jonathan Muschalle on 2015-03-01.
//  Copyright (c) 2015 Jonathan Muschalle. All rights reserved.
//

import UIKit
import AVFoundation


class TakePictureController: UICollectionViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    
    let PICTURE_DELETE_BUTTON_WIDTH:CGFloat = 43
    let PICTURE_DELETE_BUTTON_ANIMATION_DURATION:NSTimeInterval = 0.3
    let PICTURE_DELETE_BUTTON_ANIMATION_DELAY:NSTimeInterval = 0
    let CAMERA_ICON_FONT_SIZE:CGFloat = 30
    
    let captureSession = AVCaptureSession()
    var captureDevice : AVCaptureDevice?
    var controller: UIImagePickerController?

    @IBOutlet var picturesCollectionView: [UICollectionView]!
    
    override func viewDidLoad() {
        FancyTools.authentication(self)
        super.viewDidLoad()
    }
    
    override func viewDidAppear(animated: Bool) {
        FancyTools.authentication(self)
        self.collectionView?.reloadData()
    }
    
    
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return pictureListToAdd.getTotalPictures()+1
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        var currentCell = collectionView.dequeueReusableCellWithReuseIdentifier("PictureCell", forIndexPath: indexPath) as PictureCell
        
        if(pictureListToAdd.hasIndex(indexPath.row)) {
            let currentPicToAdd = pictureListToAdd.getPictureById(indexPath.row)
            currentCell.index = indexPath.row
            renderPictureToAddCell(currentPicToAdd, cell: currentCell)
        } else {
            renderHowToPictureCell(currentCell)
        }
        return currentCell
    }
    
    func renderHowToPictureCell(cell: PictureCell) {
        showHowToCell(cell)
        hidePictureCell(cell)
        cell.iconAdvice.font = UIFont.fontAwesomeOfSize(CAMERA_ICON_FONT_SIZE)
        cell.iconAdvice.text = String.fontAwesomeIconWithName(FontAwesome.CameraRetro)
        
        
    }
    
    func renderPictureToAddCell(picture: PictureToAdd, cell: PictureCell) {
        hideHowToCell(cell)
        showPictureCell(cell)
        cell.picture.image = picture.getImageObject()
        cell.picture.contentMode = UIViewContentMode.ScaleAspectFit
        cell.picture.clipsToBounds = true
//        addTapGestureOnPicture(cell)
        addDeleteButtonTargetOnPicture(cell)
    }
    
    func showHowToCell(cell: PictureCell) {
        cell.adviceText.hidden = false
        cell.adviceText.hidden = false
        cell.takePictureButton.hidden = false
        cell.iconAdvice.hidden = false
    }
    
    func hideHowToCell(cell: PictureCell) {
        cell.adviceText.hidden = true
        cell.adviceText.hidden = true
        cell.takePictureButton.hidden = true
        cell.iconAdvice.hidden = true
    }
    
    func hidePictureCell(cell: PictureCell) {
        cell.picture.hidden = true
        cell.deleteButton.hidden = true
    }
    
    func showPictureCell(cell: PictureCell) {
        cell.picture.hidden = false
        cell.deleteButton.hidden = false
    }
    
    func addTapGestureOnPicture(cell: PictureCell) {
        let aSelector : Selector = "showDeleteButton:"
        let tapGesture = UITapGestureRecognizer(target: self, action: aSelector)
        tapGesture.numberOfTapsRequired = 1
        cell.addGestureRecognizer(tapGesture)
    }
    
    func addDeleteButtonTargetOnPicture(cell: PictureCell) {
        cell.deleteButton.tag = cell.index
        cell.deleteButton.addTarget(self, action: "deletePicture:", forControlEvents: UIControlEvents.TouchUpInside)
    }
    
    @IBAction func deletePicture(sender: AnyObject) {
        let tag = sender.tag as Int
        pictureListToAdd.deletePictureByIndex(tag)
        self.collectionView?.reloadData()
    }
    
    @IBAction func showDeleteButton(sender: AnyObject) {

        let currentCell = sender.view as PictureCell

        var yDestination:CGFloat = 0
        if(currentCell.deleteButtonVisible == false) {
            yDestination = currentCell.deleteButton.center.y - PICTURE_DELETE_BUTTON_WIDTH
        } else {
            yDestination = currentCell.deleteButton.center.y + PICTURE_DELETE_BUTTON_WIDTH
        }
        animateDeleteButtonVertical(currentCell, yTo: yDestination)
        
    }
    
    func animateDeleteButtonVertical(cell: PictureCell, yTo: CGFloat) {
        UIView.animateWithDuration(PICTURE_DELETE_BUTTON_ANIMATION_DURATION,
            delay: PICTURE_DELETE_BUTTON_ANIMATION_DELAY,
            options: UIViewAnimationOptions.CurveEaseInOut | UIViewAnimationOptions.AllowUserInteraction,
            animations: {
                cell.deleteButton.center = CGPoint(x: cell.deleteButton.center.x, y: yTo)
            },
            completion: { finished in
                self.toggleVisibleDeleteButton(cell)
        })
    }
    
    func toggleVisibleDeleteButton(cell: PictureCell) {
        if (cell.deleteButtonVisible == false) {
            cell.deleteButtonVisible = true
        } else {
            cell.deleteButtonVisible = false
        }
    }
    
    @IBAction func takePictureFromCamera(sender: AnyObject) {
        
        if isCameraAvailable() {
            
            controller = UIImagePickerController()
            
            if let imagePickerController = controller {
                imagePickerController.sourceType = .Camera
                imagePickerController.delegate = self
                presentViewController(imagePickerController, animated: true, completion: nil)
            }
            
        } else {
            println("Camera is not available")
        }
    }
    
    func imagePickerController(picker: UIImagePickerController,
        didFinishPickingMediaWithInfo info: [NSObject : AnyObject]){
            
            let mediaType:AnyObject? = info[UIImagePickerControllerMediaType]
            
            if let type:AnyObject = mediaType{
                
                if type is String{
                    let stringType = type as String
                   
                    let metadata = info[UIImagePickerControllerMediaMetadata]
                        as? NSDictionary
                    if let theMetaData = metadata{
                        let image = info[UIImagePickerControllerOriginalImage]
                            as? UIImage
                        if let theImage = image {
                            pictureListToAdd.addPictureFromImage(theImage)
                            self.collectionView?.reloadData()

                        }
                    }
                    
                }
            }
            
            picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    func isCameraAvailable() -> Bool{
        return UIImagePickerController.isSourceTypeAvailable(.Camera)
    }
    
    @IBAction func home(sender: AnyObject) {
        self.dismissViewControllerAnimated(true, completion: nil)
//        var storyboard = UIStoryboard(name: "Main", bundle: nil)
//        var controller = storyboard.instantiateViewControllerWithIdentifier("main") as UIViewController
//        self.presentViewController(controller, animated: true, completion: nil)
    }

}